<template>
	<view class="content">
		<u-navbar placeholder title="发红包" autoBack></u-navbar>
		<view class="tab">
			<view>
				<view class="tab-item" v-if="groupId" @tap="show=true">
					<view>{{selectType.name}}</view>
					<u-icon name="arrow-down" color="#333333" size="32rpx"></u-icon>
				</view>
			</view>
			
			<view class="tab-item" @tap="payShow=true">
				<view>{{payType.name}}</view>
				<u-icon name="arrow-down" color="#333333" size="32rpx"></u-icon>
			</view>
		</view>
		<template v-if="groupId">
		<view class="num-box input-box" v-if="selectType.id!=3" >
			<view>
				<image :src="redIcon" />
				<view>红包个数</view>
			</view>
			<view>
				<input type="number" :maxlength="4" placeholder="填写红包个数" @input="countInput" v-model="form.count" />
				<view>个</view>
			</view>
		</view>
		<view class="num-box input-box" v-else>
			<view>
				发给谁
			</view>
			<u-icon name="arrow-right" color="#333333" size="32rpx"></u-icon>
		</view>
		<view class="tips" v-if="selectType.id!=3">本群共{{memberCount}}人</view>
		</template>
		<view class="price-box input-box" v-if="">
			<view>{{selectType.id==1?'总金额':(selectType.id==3?'金额':'单个金额')}}</view>
			<view class="flex">
				<!-- <view v-if="form.sumPrice!==''">￥</view> -->
				<input :maxlength="14" @input="pricInput($event,'sumPrice')" v-if="selectType.id!=2"
					v-model="form.sumPrice" placeholder="￥0.00" />
				<input :maxlength="14" v-else v-model="form.unitPrice" @input="pricInput($event,'unitPrice')"
					placeholder="￥0.00" />
			</view>

		</view>
		<view class="remark-box input-box">
			<input v-model="form.remark" :maxlength="20" placeholder="请输入备注" />
		</view>
		<view class="sum red">
			<text class="sum-unit">￥</text>
			<text class="sum-price">{{sumPrice||'0.00'}}</text>
		</view>
		<view class="btn" @tap="payRed">塞钱进红包</view>
		<u-action-sheet @select="selectRedType" @close="show=false" :round="10" safeAreaInsetBottom cancelText="取消"
			:actions="list" :show="show"></u-action-sheet>
		<u-action-sheet @select="payRedType" @close="payShow=false" :round="10" safeAreaInsetBottom cancelText="取消"
			:actions="payList" :show="payShow"></u-action-sheet>
		<!-- 支付弹出层 -->
		<u-popup :round="10" :show="payPriceShow" @close="payPriceShow=false">
			<view class="win-box">
				<u-icon name="close" color="#999" size="32" @click="payPriceShow=false"></u-icon>
				<view class="title">【{{payType.name}}】红包</view>
				<view class="sum ">
					<text class="sum-unit">￥</text>
					<text class="sum-price">{{sumPrice||'0.00'}}</text>
				</view>
				<view class="pay-text">
					<view>付款方式</view>
					<view>{{payType.name}}(可用：565655)</view>
				</view>
				<view class="btn" @tap="paySuccess">支付</view>
			</view>
		</u-popup>
	</view>
</template>

<script setup lang="ts">
	import { onLoad } from "@dcloudio/uni-app";
	import TUIChatEngine ,{ TUIChatService,TUIStore, StoreName } from "@tencentcloud/chat-uikit-engine";
	import { times } from '../../../utils/index'
	import { computed, nextTick, onMounted, onUnmounted, reactive, ref, watchEffect } from "../../../adapter-vue";
	import redIcon from "../../../assets/icon/red-send-icon.png";
	import { TUIGlobal } from "@tencentcloud/universal-api";
	let userId=ref('')
	let groupId=ref('')
	let memberCount=ref('')
	//当前发红包的用户信息
	let currentUser=ref({})
	//专属红包用户信息
	let userInfo = ref<any>(uni.getStorageSync(''))
	//支付弹窗
	let payPriceShow = ref(false)
	//选择红包类型
	let payShow = ref(false)
	//选择支付钱包类型
	let show = ref(false)
	let form = ref<any>({
		remark: '恭喜发财，大吉大利',
		unitPrice: '',
		count: '',
		sumPrice: '',
	})
	let selectType = ref<any>({})
	let payType = ref<any>({})
	const payList = reactive([
		// 	{
		// 	name: '现金',
		// 	color: '#333',
		// 	id: 1,
		// 	fontSize: '34rpx'
		// }, 
		{
			name: '余额',
			color: '#333',
			fontSize: '34rpx',
			id: 2,
		}, {
			name: '预消费',
			color: '#333',
			fontSize: '34rpx',
			id: 3,
		}])
	const list = reactive([{
		name: '拼手气红包',
		color: '#333',
		id: 1,
		fontSize: '34rpx'
	}, {
		name: '普通红包',
		color: '#333',
		fontSize: '34rpx',
		id: 2,
	}, {
		name: '专属红包',
		color: '#333',
		fontSize: '34rpx',
		id: 3,
	}])
	selectType.value = list[0]
	payType.value = payList[1]
	
	// UI 层监听网络变更通知
	let userProfileChange = function(res) {
		console.log(res,'当前登录用户')
	  currentUser.value=res
	}
	
	onMounted(() => {
	  TUIStore.watch(StoreName.USER, {
	    userProfile: userProfileChange,
	  })
	
	});
	onUnmounted(() => {
	  TUIStore.unwatch(StoreName.USER, {
	   userProfile: userProfileChange,
	  });
	});

	const money = (val) => {
		let value = val;
		//先去掉￥
		if (value.indexOf('￥') != -1) {
			value = value.replace(/￥/g, '')
		}
		//第一位就是 . 补零
		if (value.indexOf('.') == 0) {
			value = '0' + value
		}
		//第一位是0 并且长度大于一  第二位不是小数点 删除零
		if (value.indexOf('0') == 0 && value.length > 1 && value.indexOf('.') != 1) {
			value = value.replace(/^0+/, '');
		}
		// 限制只能输入数字和小数点
		value = value.replace(/[^\d.]/g, '');
		// 限制只有一个小数点
		value = value.replace(/\.{2,}/g, '.');
		// 限制小数点后只能有两位
		value = value.replace(/^(\d+)\.(\d{2}).*$/, '$1.$2');
		if (value !== '') {
			value = '￥' + value
		}
		return value
	}
	const pricInput = (e, keyNmae) => {
		nextTick(() => {
			console.log(form.value, "form.value")
			form.value[keyNmae] = money(e.detail.value)
		})

	}
	//限制输入正整数
	const countInput = (e) => {
		nextTick(() => {
			let value = e.detail.value
			// 如果输入第一位的是0，长度大于1
			if (value.indexOf('0') == 0) {
				value = value.replace(/^0+/, '');
			}
			// 删除负号
			if (value.indexOf('-') != -1) {
				value = value.replace(/^-/, '');
			}
			form.value.count = value
		})
	}
	const sumPrice = computed(() => {
		let price = '0.00'
		if (selectType.value.id === 1 || selectType.value.id === 3) {
			price = form.value.sumPrice.indexOf('￥') != -1 ? form.value.sumPrice.replace(/￥/g, '') : form.value.sumPrice
		} else {
			//普通红包
			let unitPrice = form.value.unitPrice.indexOf('￥') != -1 ? form.value.unitPrice.replace(/￥/g, '') : form.value.unitPrice

			price = (!Number(unitPrice) || !Number(form.value.count)) ? 0 : times(unitPrice, form.value.count)
		}
		console.log(price, "price")
		return price;
	})
	const formSet = () => {
		form.value.unitPrice = ''
		form.value.count = ''
		form.value.sumPrice = ''
	}
	const selectRedType = e => {
		selectType.value = e
		formSet()
		show.value = false
	}
	const payRedType = e => {
		payType.value = e
		formSet()
		payShow.value = false
	}
	//塞钱进红包
	const payRed = () => {
		let count = Number(form.value.count)
		//如果是拼手气红包
		if (selectType.value.id !== 3 && !count&&groupId.value) {
			return uni.showToast({
				title: '请输入红包个数',
				icon: 'none'
			})
		}
		if (selectType.value.id !== 3 &&groupId.value&&count>memberCount.value) {
			return uni.showToast({
				title: '红包个数不能大于群成员人数',
				icon: 'none'
			})
		}
		if (selectType.value.id === 3 && !userInfo.value.id&&groupId.value) {
			return uni.showToast({
				title: '请选择专属红包发给谁',
				icon: 'none'
			})
		}
		let num = form.value.sumPrice.indexOf('￥') != -1 ? form.value.sumPrice.replace(/￥/g, '') : form.value.sumPrice
		let num2 = form.value.unitPrice.indexOf('￥') != -1 ? form.value.unitPrice.replace(/￥/g, '') : form.value.unitPrice
		if (selectType.value.id !== 2 && (!Number(num))) {
			return uni.showToast({
				title: '请输入红包金额',
				icon: 'none'
			})
		}
		if (selectType.value.id === 2 && !Number(num2)) {
			return uni.showToast({
				title: '请输入单个红包金额',
				icon: 'none'
			})
		}
		if (!form.value.remark) {
			return uni.showToast({
				title: '请输入红包备注',
				icon: 'none'
			})
		}
		
		payPriceShow.value = true
	}
	//确认支付
	const paySuccess=e=>{
		uni.showToast({
			title: '支付成功',
			icon: 'none'
		})
		payPriceShow.value = false
		let promise = TUIChatService.sendCustomMessage({
			to:userId.value||groupId.value,
			conversationType:userId.value?TUIChatEngine.TYPES.CONV_C2C:TUIChatEngine.TYPES.CONV_GROUP,
		  payload: {
		    data: JSON.stringify({
		      businessID: "redPacket",
		      remark:form.value.remark,
		      unitPrice: form.value.unitPrice,
		      count:form.value.count,
		      sumPrice:sumPrice.value,
			  redType:selectType.value.id,
			  payType:payType.value.name,
			  currentUser:currentUser.value,
			  userId:userId.value,
			  groupId:groupId.value,
			  messageForShow:'['+payType.value.name+'红包]'+form.value.remark
		    }),
		  }
		});
		promise.catch((error) => {
		  // 调用异常时业务侧可以通过 promise.catch 捕获异常进行错误处理
		});

		setTimeout(()=>{
			TUIGlobal?.navigateBack()
		},800)
	}
	onLoad((options:any)=>{
		userId.value=options.userId
		groupId.value=options.groupId
		memberCount.value=options.groupCount
	})
</script>

<style lang="scss" scoped>
	::v-deep .u-action-sheet__item-wrap__item {
		padding: 30rpx 15rpx !important;
	}

	.content {
		padding:0 48rpx;
		box-sizing: border-box;

		.tab {
			display: flex;
			justify-content: space-between;
			align-items: center;
			margin-top: 20rpx;
		}

		.tab-item {
			display: flex;
			align-items: center;

			>view {
				color: #FA3121;
				margin-right: 10rpx;
			}
		}
	}

	.input-box {
		background: #fff;
		height: 115rpx;
		padding: 0 35rpx;
		margin-top: 20rpx;
		display: flex;
		align-items: center;
	}

	.num-box {
		justify-content: space-between;

		>view {
			display: flex;
			align-items: center;
		}

		image {
			width: 53rpx;
			height: 53rpx;
			margin-right: 20rpx;
		}

		input {
			width: max-content;
			// max-width: 90%;
			text-align: right;
			margin-right: 10rpx;
		}
	}

	.tips {
		margin-top: 20rpx;
		color: #999;
	}

	.price-box {
		justify-content: space-between;

		input {
			text-align: right;
		}
	}

	.red {
		color: #FA3121;
		margin-top: 160rpx;
	}

	.sum {

		text-align: center;
		font-weight: bold;


		.sum-unit {
			font-size: 70rpx;
		}

		.sum-price {
			font-size: 90rpx;
		}
	}

	.btn {
		width: 517rpx;
		height: 108rpx;
		background: linear-gradient(90deg, #FA3121 0%, #FC7844 100%);
		margin: 30rpx auto;
		border-radius: 16rpx;
		color: #fff;
		font-size: 34rpx;
		line-height: 108rpx;
		text-align: center;
	}

	.flex {
		display: flex;
	}

	.win-box {
		padding: 20rpx;
		box-sizing: border-box;

		.title {
			width: 100%;
			text-align: center;
			font-size: 34rpx;
			font-weight: bold;
		}

		.pay-text {
			padding: 36rpx 0;
			margin-top: 36rpx;
			border-top: 1px solid #E6E6E6;
			display: flex;
			justify-content: space-between;
			color: #B8B8B8;
			font-size: 38rpx;
		}

		.btn {
			margin-top: 120rpx;
		}
	}
	.remark-box{
		input{
			width: 100%;
		}
	}
</style>